AppGroup allows data sharing between two different apps or even app and widgets by creating one common shared path (like document directory). Data saved over there can be accessed by any app which is associated with that particular AppGroup. It is an offline data sharing between apps.
// 设置 let groupDefault =UserDefaults(suiteName: "自定义的App Group Id") groupDefault?.set("测试结果", forKey: "groupKey") groupDefault?.synchronize()
// 使用 let groupDefault =UserDefaults(suiteName: "自定义的App Group Id") groupDefault?.value(forKey: "groupKey")
示例:
1 2 3 4 5 6 7 8
// 设置 let groupDefault =UserDefaults(suiteName: "group.io.agora.api.example.kilomind") groupDefault?.set(channelName, forKey: "channelName") groupDefault?.synchronize()
// 使用 let groupDefault =UserDefaults(suiteName: "group.io.agora.api.example.kilomind") let channel = groupDefault?.value(forKey: "channelName") as?String
大量数据的共享,使用FileManager
1 2 3 4 5 6 7 8
// 设置 let containerURL =FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "自定义的App Group Id") let logsPath = containerURL!.appendingPathComponent("ShareGroup")
// 使用 let documentsDirectory =FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "自定义的App Group Id") let replayPath = documentsDirectory?.appendingPathComponent("/ShareGroup") let directoryContents =try!FileManager.default.contentsOfDirectory(at: replayPath!, includingPropertiesForKeys: nil, options: [])
示例:
1 2 3 4 5 6 7 8 9
// 设置 let groupUrl =FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.io.agora.api.example.kilomind")!.appendingPathComponent("Library/Preferences") let fileUrl = groupUrl.appendingPathComponent("appGroup.txt") try! channelName.write(to: fileUrl, atomically: true, encoding: .utf8)
// 使用 let groupUrl =FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.io.agora.api.example.kilomind")!.appendingPathComponent("Library/Preferences") let fileUrl = groupUrl.appendingPathComponent("appGroup.txt") let text =try?String(contentsOf: fileUrl, encoding: .utf8)